package com.jinly.ryder.ssh.service.impl;

import com.jcraft.jsch.Session;
import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.ssh.command.CommonCommand;
import com.jinly.ryder.ssh.command.SshSessionUtil;
import com.jinly.ryder.ssh.service.SshCommandService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SshCommandServiceImpl implements SshCommandService {


    @Override
    public List<String> command(String host, int port, String command) {
        Session sshSession = null;
        try {
            sshSession = SshSessionUtil.connectSession(host, port);
            CommonCommand commonCommand = new CommonCommand(sshSession);
            return commonCommand.exec(command);
        } catch (Exception e) {
            log.warn("ssh file close:{}", e.getMessage());
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError();
        } finally {
            SshSessionUtil.closeSession(sshSession);
        }
        return null;
    }
}
